package net.sinmetal.twitcockpit.controller.twitter;

import net.sinmetal.twitcockpit.model.config.AuthUser;
import net.sinmetal.twitcockpit.service.ConfigService;
import net.sinmetal.twitcockpit.twitter.Twitter4tc;
import net.sinmetal.twitcockpit.twitter.Twitter4tcFactory;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.util.AppEngineUtil;
import org.slim3.util.RequestMap;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * TwitterTweetController
 *
 * @author Sinmetal
 *
 */
public class TweetController extends Controller {

    private ConfigService configService = new ConfigService();

    /**
     * つぶやく
     */
    @Override
    public Navigation run() throws Exception {
        UserService userService = UserServiceFactory.getUserService();
        if (!userService.isUserLoggedIn()) {
            response.sendRedirect(userService.createLoginURL("/"));
            return null;
        }
        User user = userService.getCurrentUser();
        AuthUser authUser = configService.getAuthUser();
        if (!authUser.constains(user)) {
            return redirect("/error/notFound.html");
        }

        final String TOP_PAGE = "/";
        RequestMap requestMap = new RequestMap(request);
        if (!validate(requestMap)) {
            return forward(TOP_PAGE);
        }

        String twitterID = "test4sinmetal";
        if (AppEngineUtil.isProduction()) {
            twitterID = "chugokugtug";
        }
        Twitter4tc twitter4tc = new Twitter4tcFactory().getInstance(twitterID);

        String tweet = requestScope("tweet");
        twitter4tc.updateStatus(tweet);
        return redirect(TOP_PAGE);
    }

    /**
     * validate
     *
     * @param requestMap
     * @return
     */
    private boolean validate(RequestMap requestMap) {
        Validators v = new Validators(requestMap);
        v.add("tweet", v.required(), v.maxlength(140));
        return v.validate();
    }

}
